/**
 *  @name list_page_mixins
 *  @author liubo
 *  @description 查询、表格组件引入; 分页; 获取表格数据；统计（商户定制） 
 */

import MerSearch from '@/components/work/MerSearch'
import MerTable from '@/components/work/MerTable'
import { findConfigIndex, exportSearchList } from '@/utils/listTools.js'

export default {
  components:{
    MerSearch,
    MerTable
  },
  data () {
    return {
      searchBar: {},   //查询表单容器
      downloadParams:{}, //用于对查询条件做缓存
      tableLoading: false,
      tableData: { // 表格
        records: [],    //列表数据
        total: 0        //总条数 
      },
      pagination: {   // 分页参数
        // page: true,    //是否分页，导出传false
        pageIndex: 1,     //页码数，起始页 
        pageSize: 10   //每页显示个数
      },
      pageSizes: [10, 50, 100, 200],
      sumInfo:{}  //汇总（统计）容器 ｜ 默认值引用页面覆写
    }
  },
  methods: {
    /**
     * 初始化列表页
     * @param {Promise} lisApi 列表查询接口 （required）
     * @param {Object} otherParams 其他额外参数
     * @param {Boolean} hasSum 是否需要汇总
     * @param {Promise} sumApi 汇总信息接口
     */
    initList (lisApi, hasSum = false, sumApi, otherParams = {}) {
      this.$_listApi = lisApi
      this.$_otherParams = otherParams
      this.$_hasSum = hasSum
      this.$_SumApi = sumApi || new Promise((resolve)=>{
        resolve()
      })
      this.search()
    },
    // pageIndex改变
    pageChange (currentPage) {
      this.pagination.pageIndex = currentPage
      this.refresh()
    },
    // pageSize改变
    handleSizeChange (pageSize) {
      this.pagination.pageSize = pageSize
      this.pagination.pageIndex = 1
      this.refresh()
    },
    /**
     * 查询列表
     */
    search () {
      this.pagination.pageIndex = 1
      // this.pagination.pageSize = 10
      this.refresh()
    },
    /**
     *  表格重置
     * @param {Function} initQuery 查询条件初始化
     */
    reset (initQuery, searchName = 'searchBar') {
      this.$data[searchName] = {}
      // Object.keys(this.$data[searchName]).forEach(key => {
      //   this.$data[searchName][key] = ''
      // })
      if (initQuery && (typeof initQuery === 'function')) {
        initQuery()
      }
      this.search()
    },
     // 获取table ||  特殊的请求或数据处理，可以覆写该方法
    async refresh () {
      this.tableLoading = true
      const data = { ...this.searchBar, ...this.pagination, ...this.$_otherParams}
      //对查询条件做一次缓存
      this.downloadParams = { ...this.searchBar,...this.$_otherParams }
      if (this.$_hasSum) {
        this.getSumInfo(data)
      }
      try{
        const { code, result = [], totalRow = 0 } = await this.$_listApi(data)
        if(code !== 200) return
        this.tableData.records = result
        this.tableData.total = parseInt(totalRow)
      }catch(err){
        console.log(err)
      }finally{
        this.tableLoading = false
      }
    },
    // 列表汇总（统计）信息
    async getSumInfo (data) {
      try{
        const { code, result } = await this.$_SumApi(data)
        if(code !== 200) return
        this.sumInfo = result || {}
      }catch(err){
        console.log(err)
      }
    },
    // 筛选需要的表单配置项
    findConfigIndex (formArr = [],modelName) {
      let index = formArr.findIndex((value) => {
        return value.modelName === modelName
      })
      return index !== -1 ? index : ''
    },
    /**
     * 设置search_config
     * @param { Object } initObj  需要初始化的数据
     *  {modelName,value}
     *  select类型，value为 selectOptions
     *  date类型，value为 [model,pickerOptions]
     * @param { String } formConfig   data中的查询表单配置名，可不传
     */
    setSearchConfig(initObj, formConfig = 'formConfig'){
      let formArr = this.$data[formConfig]
      Object.keys(initObj).forEach( key =>{
        const index = findConfigIndex(formArr,key)
        if(index === '') return
        switch(formArr[index].type){
          case 'select': 
            formArr[index].selectOptions = initObj[key]
            break
          case 'date':
            formArr[index].model = initObj[key][0]
            formArr[index].pickerOptions = initObj[key][1] || {}
        }
      })
    },
    /**
     *  时间change
     * @param {Array} value 选择的值
     * @param {String} name searchBar(查询表单对象)
     * @param {String} startTime 开始时间 默认startTime
     * @param {String} endTime 结束时间  默认endTime
     */
    changeTime (value, name, startTime = 'startTime', endTime = 'endTime') {
      let searchObj = this.$data[name]
      if (value) {
        searchObj[startTime] = value[0]
        searchObj[endTime] = value[1]
      } else {
        searchObj[startTime] = ''
        searchObj[endTime] = ''
      }
    },
    /**
     *  导出
     * @param {Function} dowanloadApi 下载接口
     * @param {String} name 导出文件名称 
     * @param {Object} otherParams 查询参数以外所需的额外参数
     */
    async downloadFile (dowanloadApi,name,otherParams = null) {
      try{
        let data = otherParams ? {...otherParams} : {...this.downloadParams}
        const { code, result = {} } = await dowanloadApi(data)
        if(code !== 200) return
        exportSearchList(result.file, result.fileName || name)
      }catch(err){
        console.log(err)
      }
    },
  }
}
